from django.views.generic import TemplateView
from accounts.utils.data_analysis import SurveyAnalyzer
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, Line, Radar, Gauge, Funnel
from pyecharts.globals import ThemeType
import random


class RiskAnalysisView(TemplateView):
    template_name = 'charts/risk_analysis.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        analyzer = SurveyAnalyzer()
        risk_data = analyzer.analyze_risks()

        # 创建风险行为分布饼图
        risk_dist = risk_data['risk_distribution']
        risk_pie = (
            Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add(
                "风险分布",
                [list(z) for z in zip(risk_dist.keys(), risk_dist.values())],
                radius=["30%", "70%"],
                center=["50%", "50%"],
                label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"),
            )
            .set_global_opts(
                # title_opts=opts.TitleOpts(title="青少年风险行为级别分布"),
                legend_opts=opts.LegendOpts(orient="vertical", pos_left="left")
            )
        )
        context['risk_distribution_chart'] = risk_pie.render_embed()

        # 创建风险行为类型柱状图
        risk_scores = risk_data['risk_avg_scores']
        risk_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(list(risk_scores.keys()))
            .add_yaxis("平均分值", list(risk_scores.values()), category_gap="50%")
            .set_series_opts(label_opts=opts.LabelOpts(position="top"))
            .set_global_opts(
                # title_opts=opts.TitleOpts(title="不同风险行为平均分值"),
                xaxis_opts=opts.AxisOpts(name="风险类型"),
                yaxis_opts=opts.AxisOpts(name="平均分值", min_=0, max_=5)
            )
        )
        context['risk_types_chart'] = risk_bar.render_embed()

        # 创建年龄段风险行为趋势折线图
        age_risk = risk_data['age_risk_trend']
        age_groups = risk_data['age_groups']

        age_line = (
            Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(age_groups)
        )

        for risk_type, values in age_risk.items():
            age_line.add_yaxis(
                risk_type,
                values,
                is_smooth=True,
                label_opts=opts.LabelOpts(is_show=False),
                linestyle_opts=opts.LineStyleOpts(width=2)
            )

        age_line.set_global_opts(
            # title_opts=opts.TitleOpts(title="不同年龄段风险行为趋势"),
            xaxis_opts=opts.AxisOpts(name="年龄段"),
            yaxis_opts=opts.AxisOpts(name="风险程度", min_=0, max_=5),
            legend_opts=opts.LegendOpts(orient="horizontal", pos_top="top")
        )
        context['age_risk_chart'] = age_line.render_embed()

        # 创建性别风险行为对比雷达图
        gender_risk = risk_data['gender_risk_diff']
        risk_types = list(list(gender_risk.values())[0].keys())

        radar = (
            Radar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=risk, max_=5) for risk in risk_types
                ],
                splitarea_opt=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=0.1)
                ),
            )
        )

        for gender, values in gender_risk.items():
            radar.add(
                gender,
                [[values[risk] for risk in risk_types]],
                linestyle_opts=opts.LineStyleOpts(width=2)
            )

        radar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        radar.set_global_opts(
            # title_opts=opts.TitleOpts(title="性别风险行为差异"),
            legend_opts=opts.LegendOpts(selected_mode='multiple')
        )
        context['gender_risk_chart'] = radar.render_embed()

        # 创建风险因素相关性柱状图
        corr_data = risk_data['risk_correlations']
        corr_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(list(corr_data.keys()))
            .add_yaxis("相关系数", list(corr_data.values()), category_gap="50%")
            .set_series_opts(
                label_opts=opts.LabelOpts(position="top"),
                itemstyle_opts=opts.ItemStyleOpts(
                    color=lambda x: "rgba(59,85,230,0.8)" if x.data >= 0.5 else "rgba(220,69,50,0.8)"
                )
            )
            .set_global_opts(
                # title_opts=opts.TitleOpts(title="风险行为相关因素分析"),
                xaxis_opts=opts.AxisOpts(name="影响因素", axislabel_opts=opts.LabelOpts(rotate=15)),
                yaxis_opts=opts.AxisOpts(name="相关系数", min_=0, max_=1)
            )
        )
        context['risk_correlation_chart'] = corr_bar.render_embed()

        # 创建风险行为后果预测漏斗图
        conseq_data = risk_data['risk_consequences']
        sorted_conseq = sorted(conseq_data.items(), key=lambda x: x[1], reverse=True)

        funnel = (
            Funnel(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add(
                "风险后果",
                [list(item) for item in sorted_conseq],
                label_opts=opts.LabelOpts(formatter="{b}: {c}")
            )
            .set_global_opts(
                # title_opts=opts.TitleOpts(title="风险行为可能导致的后果"),
                legend_opts=opts.LegendOpts(orient="vertical", pos_left="left")
            )
        )
        context['risk_consequences_chart'] = funnel.render_embed()

        # 创建风险趋势预测折线图
        trend_data = risk_data['risk_trend_prediction']
        years = risk_data['years']

        trend_line = (
            Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(years)
        )

        for risk_type, values in trend_data.items():
            trend_line.add_yaxis(
                risk_type,
                values,
                is_smooth=True,
                label_opts=opts.LabelOpts(is_show=False),
                linestyle_opts=opts.LineStyleOpts(width=2),
                markpoint_opts=opts.MarkPointOpts(
                    data=[
                        opts.MarkPointItem(type_="max", name="最大值"),
                        opts.MarkPointItem(type_="min", name="最小值"),
                    ]
                )
            )

        trend_line.set_global_opts(
            # title_opts=opts.TitleOpts(title="风险行为趋势预测"),
            xaxis_opts=opts.AxisOpts(name="年份"),
            yaxis_opts=opts.AxisOpts(name="风险程度", min_=0, max_=5),
            legend_opts=opts.LegendOpts(orient="horizontal", pos_top="top"),
            toolbox_opts=opts.ToolboxOpts(
                is_show=True,
                feature=opts.ToolBoxFeatureOpts(
                    save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(title="保存为图片"),
                    data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=True),
                    brush=opts.ToolBoxFeatureBrushOpts(type_="clear"),
                )
            )
        )
        context['risk_trend_chart'] = trend_line.render_embed()

        # 添加风险行为洞察
        context['risk_insights'] = [
            {
                "title": "年龄是风险行为的关键预测因素",
                "content": "研究数据显示，随着年龄增长，青少年的风险行为尤其是饮酒行为呈明显上升趋势。16-18岁是风险行为形成的关键期，应加强这一阶段的预防干预工作。"
            },
            {
                "title": "性别差异在风险行为中的表现",
                "content": "男性青少年在饮酒和药物使用方面的风险得分普遍高于女性，而女性在死亡话题关注和生死观念方面的得分略高，这反映了不同性别的心理特点差异。"
            },
            {
                "title": "心理健康与风险行为的高度相关性",
                "content": "数据分析显示，心理健康状况与青少年风险行为呈现强相关性，心理健康问题是导致高风险行为的重要因素之一，预防工作应关注心理健康的筛查和早期干预。"
            },
            {
                "title": "家庭关系对风险行为的保护作用",
                "content": "良好的家庭关系是预防青少年风险行为的重要保护因素，数据显示家庭关系与风险行为呈负相关，家庭教育和亲子关系建设应成为风险预防的重要内容。"
            },
            {
                "title": "未来风险行为趋势预测",
                "content": "综合分析表明，未来几年青少年综合风险行为可能有小幅上升趋势，特别是在数字化媒体和网络环境影响下，应关注新型风险行为的出现和演变。"
            }
        ]

        # 设置导航标识
        context['navname'] = 'risk'

        return context
